/**
 * [countdown 倒计时]
 * @param  {Number}   limit    [倒计时时间 单位:秒]
 * @param  {Function} onChange [每秒回调]
 * @param  {Function} onOver   [结束回调]
 * @return {Timer}             [计时器,可以自定义清除]
 */
export default function countdown (limit, onChange = f => f, onOver = f => f) {
  let timer = null
  let index = limit

  if (limit <= 0) {
    onOver(0)

    return
  }

  onChange(index)

  timer = setInterval(() => {
    index -= 1

    if (index <= 0) {
      onChange(index)
      onOver(index)

      clearInterval(timer)
      timer = null

      return
    }

    onChange(index)
  }, 1000)

  return timer
}
